package com.hospital.interceptor;


import com.hospital.anno.LoginAuthentication;
import com.hospital.dao.UserDao;
import com.hospital.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份验证拦截器 拦截未登录的用户
 *
 * @author yuhuan
 * @date 2022/3/23
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserDao userDao;
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 判断请求是否需要被拦截，会在方法上或者类上寻找LoginAuthentication.class
        if (IsInterceptorToPreHandle.isInterceptor(handler, LoginAuthentication.class)) {
            // 从 http 请求头中取出 token
            String token = request.getHeader("token");
            // 如果取出的值为空或者空的字符串就表示用户没有登录，需要提示或跳转到登录页面
            if (ObjectUtils.isEmpty(token) || Constants.NULL_STR.equals(token)) {
                return false;

            }
            return true;
        }
        return true;
    }
}
